package com.zuoye.text8;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NewsDaoImpl4 extends BaseDao implements NewsDao4 {



    @Override
    public List<News4> getNewsList() {
        List<News4> newList=new ArrayList<News4>();
        try {
            //（3）获得Statement对象，执行SQL语句
            String sql="select * from news_user";
            Object[] params={};
            ResultSet rs=this.executeSQL(sql, params);
            //（4）处理执行结果(ResultSet)，
            while(rs.next()){
                int id=rs.getInt("id");
                String userName=rs.getString("userName");
                String password=rs.getString("password");
                String email=rs.getString("email");
                int userType=rs.getInt("userType");

                //封装成新闻信息对象
                News4 news=new News4();
                news.setId(id);
                news.setUserName(userName);
                news.setPassword(password);
                news.setEmail(email);
                news.setUserType(userType);


                //将新闻对象放进集合中
                newList.add(news);
            }
        }catch (SQLException e) {

            e.printStackTrace();
        }finally{
            //释放资源
            this.closeResource();
        }
        return newList;
    }


    @Override
    public boolean add(News4 news) {
        boolean flag=false;
        try {
            String sql="insert into news_user(userName,password,email,userType) values(?,?,?,?)";
            Object[] params={news.getUserName(),news.getPassword(),news.getEmail(),news.getUserType()};
            int i=this.executeUpdate(sql, params);
            //（4）处理执行结果
            if(i>0){
                System.out.println("插入新闻成功！");
            }
            flag=true;
        }finally{
            //释放资源
            this.closeResource();
        }
        return flag;
    }

    @Override
    public boolean delete(int id) {
        boolean flag=false;
        try {
            String sql = "delete from  news_user where id=?";
            Object[] params={id};
            int i=this.executeUpdate(sql, params);
            //（4）处理执行结果
            if(i>0){
                System.out.println("删除新闻成功！");
            }
            flag=true;
        }  finally {
            //释放资源
            this.closeResource();
        }
        return flag;
    }

    @Override
    public boolean update(News4 news) {
        boolean flag=false;
        try {
            String sql = "update News_user set password=? where id=?";
            Object[] params={news.getPassword(),news.getId()};
            int i=this.executeUpdate(sql, params);
            //（4）处理执行结果
            if(i>0){
                System.out.println("修改新闻成功！");
            }
            flag=true;
        }  finally {
            //释放资源
            this.closeResource();
        }
        return flag;
    }
}
